<template>
  <div class="add-role">
    <el-dialog :title="editRoleId===null?'新增角色':'修改角色'" :visible.sync="isVisible"
               :before-close="handleCloseDialog" width="45%">
      <el-card style="margin: 0 auto" shadow="never">
        <div class="add-role-input">
          <el-form label-width="100px" :model="addRoleMessage" ref="addRoleFrom" :rules="rules">
            <el-form-item label="角色名：" prop="roleName">
              <el-input v-model="addRoleMessage.roleName" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色代号：" prop="roleCode">
              <el-input v-model="addRoleMessage.roleCode" maxlength="10" minlength="5" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色等级：">
              <el-select v-model="addRoleMessage.roleLevel" placeholder="请选择角色等级">
                <el-option v-for="item in roleLevelOptions" :key="item.value" :value="item.value" :label="item.level">
                  {{ item.level }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <div class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddRole(editRoleId==null?'add':'edit')">
          {{ editRoleId === null ? '确认添加' : '确认修改' }}
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import { mapState } from 'vuex'
import store from '@/store'
import {
  AddRoleApi,
  CheckAddRoleNameRepeatApi,
  CheckAddRoleRepeatApi,
  GetRoleByIdApi,
  UpdateRoleByIdApi
} from '@/request/role/role-api'

export default {
  data () {
    return {
      addRoleMessage: {
        id: null,
        roleName: '',
        roleCode: '',
        roleLevel: 0
      },
      roleLevelOptions: [
        {
          value: 0,
          level: '普通用户级'
        },
        {
          value: 1,
          level: '普通管理员级'
        },
        {
          value: 2,
          level: '超级管理员级'
        }
      ],
      rules: {
        roleName: {
          required: true,
          message: '角色名必填!',
          trigger: 'blur'
        },
        roleCode: {
          required: true,
          message: '角色代号必填！',
          trigger: 'blur'
        }
      },
    }
  },
  computed: {
    listenEditRoleId () {
      return store.state.roleEditData.editRoleId
    },
    ...mapState({
      editRoleId: state => state.roleEditData.editRoleId,
      isVisible: state => state.roleEditData.isVisible,
    })
  },
  methods: {
    closeAddOrEdit () {
      store.commit('roleEditData/changeIsVisible', false)
      store.commit('roleEditData/changeEditRoleId', null)
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addRoleFrom'].clearValidate()
      })
      this.addRoleMessage = {
        id: null,
        roleName: '',
        roleCode: '',
        roleLevel: 0
      }
    },
    async getRoleById (id) {
      let res = await GetRoleByIdApi(id)
      if (res.code === 200) {
        this.addRoleMessage.id = res.data.id
        this.addRoleMessage.roleName = res.data.roleName
        this.addRoleMessage.roleCode = res.data.roleCode
        this.addRoleMessage.roleLevel = res.data.roleLevel
      } else {
        this.$message.info('查询角色失败！')
      }
    },
    handleCloseDialog () {
      this.$confirm('确定取消操作吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(() => {
        this.closeAddOrEdit()
      }).catch((e) => {
        if (e === 'cancel') {
        }
      })
    },
    handleAddRole (type) {
      //校验表单
      this.$refs.addRoleFrom.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          //是添加角色
          if (type === 'add') {
            this.$confirm('确定添加该角色信息吗？', '提示',
                {
                  'confirmButtonText': '确定',
                  'cancelButtonText': '取消',
                  'type': 'warning'
                }).then(async () => {
              let checkRes = await CheckAddRoleRepeatApi({ roleCode: this.addRoleMessage.roleCode })
              if (checkRes.code === 200) {
                let checkRoleName = await CheckAddRoleNameRepeatApi({ roleName: this.addRoleMessage.roleName })
                if (checkRoleName.data !== null) {
                  this.$confirm('系统已经存在相同用户名，是否还要继续添加？', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                  }).then(async () => {
                    await this.addRole()
                  }).catch(e => {
                    //取消添加
                    if (e === 'cancel') {
                      this.$message.info('已取消添加角色')
                    }
                  })
                } else {
                  await this.addRole()
                }
              } else {
                //存在重复的code
                this.$message.error(checkRes.msg)
              }
            }).catch((e) => {
              if (e === 'cancel') {
                this.$message.info('已取消添加角色')
                this.closeAddOrEdit()
              } else {
                this.$message.error('未知错误！')
                this.closeAddOrEdit()
              }
            })
          } else if (type === 'edit') {
            this.updateRole()
          }
        }
      })
    },
    //修改角色
    updateRole () {
      this.$confirm('确定添加该角色信息吗？', '提示',
          {
            'confirmButtonText': '确定',
            'cancelButtonText': '取消',
            'type': 'warning'
          }).then(async () => {
        let res = await UpdateRoleByIdApi(this.addRoleMessage)
        if (res.code === 200) {
          this.$notify.success({title:'修改成功',message:'修改角色信息成功'})
        }else {
          this.$message.error(res.msg)
        }
        this.closeAddOrEdit()
        this.$parent.init()
      }).catch((e) => {
        if (e === 'cancel') {
          this.$message.info('取消修改角色')
        }
      })
    },
    //添加角色
    async addRole () {
      //提交添加
      let addRes = await AddRoleApi(this.addRoleMessage)
      if (addRes.code === 200) {
        this.$message.success('添加成功！')
        this.closeAddOrEdit()
        this.$parent.init()
      } else {
        this.$message.error(addRes.msg)
        this.closeAddOrEdit()
        this.$parent.init()
      }
    }
  },
  watch: {
    listenEditRoleId: {
      immediate: true,
      handler (val, oldval) {
        if (val) {
          this.getRoleById(val)
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.add-role {
  .el-dialog {
    .el-card {
      width: 80%;
      .add-role-input {
        width: 80%;
        margin: 10px 20px;
        .el-input {
          width: 222px;
        }
      }
    }

    .dialog-footer {
      margin: 0 auto;
      padding: 20px 20px;
      max-width: 200px;
    }
  }
}

/deep/ .el-dialog {
  border-radius: 10px;
}
</style>
